package com.item.yxlottery.yxlottery.fragment;

/*
 *------------------------------
 * @创建者      Administrator
 * @创建时间    2016/11/16 15:26
 * @文件描述    彩店fragment
 *------------------------------
 */

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baidu.location.BDLocation;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemClickListener;
import com.item.yxlottery.yxlottery.R;
import com.item.yxlottery.yxlottery.activity.SelectorCityActivity;
import com.item.yxlottery.yxlottery.activity.StoreDetailActivity;
import com.item.yxlottery.yxlottery.adapter.StoreListAdapter;
import com.item.yxlottery.yxlottery.base.BaseFragment;
import com.item.yxlottery.yxlottery.bean.StoreBean;
import com.item.yxlottery.yxlottery.callback.MyStringCallBack;
import com.item.yxlottery.yxlottery.common.Constant;
import com.item.yxlottery.yxlottery.utils.UrlUtil;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.builder.PostFormBuilder;

import java.util.ArrayList;

import butterknife.Bind;
import butterknife.ButterKnife;
import okhttp3.Call;

import static android.app.Activity.RESULT_OK;

public class StoreFragment extends BaseFragment implements View.OnClickListener {

    @Bind(R.id.tv_store_distancetext)
    TextView mTvDistanceText;

    @Bind(R.id.view_store_distanceline)
    View mViewDistanceLine;

    @Bind(R.id.all_store_distance)
    LinearLayout mAllDistance;

    @Bind(R.id.tv_store_saletext)
    TextView mTvSaleText;

    @Bind(R.id.view_store_saleline)
    View mViewSaleLine;

    @Bind(R.id.all_store_sale)
    LinearLayout mAllSale;

    @Bind(R.id.rv_store_list)
    RecyclerView mRvList;

    private ArrayList<StoreBean> mStoreList = new ArrayList<>();
    private ImageButton mIbActionbarRight;
    private BDLocation mLocation;
    private String mProvince = "";//定位得到的当前省
    private String mCity = "";//定位得到的当前市(地区)
    private boolean mLocationError;//定位失败
    private StoreListAdapter mStoreListAdapter;

    @Override
    protected View initView(LayoutInflater inflater, ViewGroup container) {
        View view = inflater.inflate(R.layout.fragment_store, container, false);
        ButterKnife.bind(this, view);
        return view;
    }

    @Override
    protected void initData() {
        mIbActionbarRight = (ImageButton) ((Activity) mContext).findViewById(R.id.ib_actionbar_right);
        setRecycleViewShow(mStoreList);
        Bundle bundle = getArguments();
        if (bundle != null) {
            BDLocation location = bundle.getParcelable("location");
            if (location != null && location.getLocType() != BDLocation.TypeServerError) {
                mLocation = location;
                mProvince = location.getAddress().province;
                mCity = location.getAddress().city;
                getStoreInfo(location, false, true, "1");
            } else {
                mLocationError = true;
                Toast.makeText(mContext, "定位失败,请手动选择当前位置!", Toast.LENGTH_SHORT).show();
            }
        }
    }

    @Override
    protected void initEvent() {
        mIbActionbarRight.setOnClickListener(this);
        mAllDistance.setOnClickListener(this);
        mAllSale.setOnClickListener(this);
        mRvList.addOnItemTouchListener(new OnItemClickListener() {
            @Override
            public void SimpleOnItemClick(BaseQuickAdapter adapter, View view, int position) {
                Intent intent = new Intent(mContext, StoreDetailActivity.class);
                intent.putExtra("store", mStoreList.get(position));
                startActivity(intent);
            }
        });
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.all_store_distance:
                mTvDistanceText.setTextColor(0xffff0000);
                mViewDistanceLine.setVisibility(View.VISIBLE);
                mTvSaleText.setTextColor(0xff333333);
                mViewSaleLine.setVisibility(View.GONE);
                if (mLocationError) {
                    Toast.makeText(mContext, "定位失败,请手动选择当前位置!", Toast.LENGTH_SHORT).show();
                } else {
                    getStoreInfo(mLocation, false, true, "1");
                }
                break;
            case R.id.all_store_sale:
                mTvSaleText.setTextColor(0xffff0000);
                mViewSaleLine.setVisibility(View.VISIBLE);
                mTvDistanceText.setTextColor(0xff333333);
                mViewDistanceLine.setVisibility(View.GONE);
                if (mLocationError) {
                    Toast.makeText(mContext, "定位失败,请手动选择当前位置!", Toast.LENGTH_SHORT).show();
                } else {
                    getStoreInfo(mLocation, true, true, "1");
                }
                break;
            case R.id.ib_actionbar_right:
                Intent intent = new Intent(mContext, SelectorCityActivity.class);
                intent.putExtra("province", mProvince);
                intent.putExtra("city", mCity);
                startActivityForResult(intent, 0);
                break;
        }
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        ButterKnife.unbind(this);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode == RESULT_OK) {
            Toast.makeText(mContext, "provinceId:" + data.getStringExtra("provinceId") + "-----" + "cityId:" + data.getStringExtra("cityId"),
                    Toast.LENGTH_SHORT).show();
        }
    }

    /*- 设置recycleview显示 -*/
    private void setRecycleViewShow(ArrayList<StoreBean> storeList) {
        mStoreListAdapter = new StoreListAdapter(mContext, R.layout.item_store_list, storeList);
        mRvList.setLayoutManager(new LinearLayoutManager(mContext));
        mRvList.setAdapter(mStoreListAdapter);
    }

    /*- 请求彩店列表信息 -*/
    private void getStoreInfo(BDLocation location, boolean sort, final boolean clear, String pageNo) {
        PostFormBuilder builder = OkHttpUtils.post().url(UrlUtil.getStoreListUrl()).addParams("storeLongitude", location.getLongitude() + "")
                .addParams("storeAtitude", location.getLatitude() + "").addParams("pageNo", pageNo).addParams("pageSize", "10");
        if (sort) {
            builder.addParams("orderBySales", "1");//销量降序排序
        }
        builder.build().execute(new MyStringCallBack(mContext, true) {
            @Override
            public void onError(Call call, Exception e, int id) {

            }

            @Override
            public void onResponse(String response, int id) {
                JSONObject parse = (JSONObject) JSON.parse(response);
                if (parse.getString("error_code").equals(Constant.SUCCESS)) {
                    if (clear) {//是否需要清除原来请求到的彩店列表信息
                        mStoreList.clear();
                    }
                    for (Object object : JSON.parseArray(parse.getString("datas"))) {
                        mStoreList.add(JSON.parseObject(object.toString(), StoreBean.class));
                    }
                    mStoreListAdapter.notifyDataSetChanged();
                }
            }
        });
    }
}
